package memorystorer

//Basic interface that sets the storage interface methods required for usage by the User model.
// This is done in memory, so is useful for mocks, but it is not persisted and so would not be useful
// for a real server implementation.

//To use this the file needs to be imported with a preceding underscore as the methods do not need to
// be called directly, but from inside the auth/models module itself.

import (
	"code.google.com/p/jesus-1496/auth/models"
	"fmt"
)

type UserStore struct {
	userCache map[string]*models.User
}

func NewUserStore() *UserStore {
	return &UserStore{make(map[string]*models.User)}
}

func (ms *UserStore) Save(u *models.User) error {
	ms.userCache[u.Email] = u
	return nil
}

func (ms *UserStore) Load(email string) (*models.User, error) {
	if user, ok := ms.userCache[email]; ok {
		return user, nil
	}
	return nil, models.NewUserError(fmt.Sprintf("No such user: ", email))
}

func (ms *UserStore) Exists(email string) bool {
	if _, ok := ms.userCache[email]; ok {
		return true
	}
	return false
}

func (ms *UserStore) Delete(email string) error {
	if _, ok := ms.userCache[email]; ok {
		delete(ms.userCache, email)
		return nil
	}
	return models.NewUserError(fmt.Sprintf("Error deleting user %s: No such user exists.", email))
}

func init() {
	models.SetUserStore(NewUserStore())
	//create a user so I can log in and shieeet.
	u, err := models.NewUser("ifross@gmail.com", "password", true)
	if err != nil {
		panic("CANNOT CREASTE USUAEADF")
	}
	err = u.Save()
	if err != nil {
		panic("CANNOT SAVE USER!!!")
	}
}
